#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>

int connfd;

void recvoob(int sig)
{
    char oob;
    recv(connfd, &oob, 1, MSG_OOB);
    fprintf(stderr, "%c", oob);
}

int main(int argc, char const *argv[])
{
    if(argc != 2)
    {
        printf("请指定绑定端口\n");
        exit(0);
    }

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    
    struct sockaddr_in myaddr;
    socklen_t len = sizeof(myaddr);
    bzero(&myaddr, len);

    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    myaddr.sin_port = htons(atoi(argv[1]));
    bind(sockfd, (struct sockaddr *)&myaddr, len);

    listen(sockfd, 0);

    struct sockaddr_in peeraddr;
	len = sizeof(peeraddr);
	bzero(&peeraddr, len);

    connfd = accept(sockfd, (struct sockaddr *)&peeraddr, &len);
    if(connfd == -1)
    {
        perror("连接失败");
        exit(0);
    }

    signal(SIGURG, recvoob);
    fcntl(connfd, __F_SETOWN, getpid());

    char buf[128];
    while (1)
    {
        bzero(buf, sizeof(buf));
        int n = read(connfd, buf, sizeof(buf));
        if(n == 0)
            break;
        printf("%s",buf);
    }
    return 0;
}